package com.scheduling.machine.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.scheduling.common.result.Result;
import com.scheduling.machine.dto.MachineDTO;
import com.scheduling.machine.dto.MachineQueryDTO;
import com.scheduling.machine.entity.Machine;
import com.scheduling.machine.service.MachineService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 机器管理控制器
 *
 * @author 开发团队
 * @since 2025-05-29
 */
@Slf4j
@RestController
@RequestMapping("/api/machine")
@Tag(name = "机器管理", description = "机器信息的增删改查操作")
public class MachineController {

    @Autowired
    private MachineService machineService;

    @Operation(summary = "分页查询机器列表", description = "根据条件分页查询机器信息")
    @PostMapping("/page")
    public Result<IPage<Machine>> getMachinePage(@RequestBody MachineQueryDTO queryDTO) {
        try {
            IPage<Machine> page = machineService.getMachinePage(queryDTO);
            return Result.success(page);
        } catch (Exception e) {
            log.error("分页查询机器列表失败：{}", e.getMessage(), e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    @Operation(summary = "根据ID获取机器详情", description = "根据机器ID获取详细信息")
    @GetMapping("/{machineId}")
    public Result<Machine> getMachineById(
            @Parameter(description = "机器ID", required = true) @PathVariable String machineId) {
        try {
            Machine machine = machineService.getMachineById(machineId);
            if (machine == null) {
                return Result.error("机器不存在");
            }
            return Result.success(machine);
        } catch (Exception e) {
            log.error("获取机器详情失败：{}", e.getMessage(), e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    @Operation(summary = "添加机器", description = "添加新的机器信息")
    @PostMapping
    public Result<String> addMachine(@Validated @RequestBody MachineDTO machineDTO) {
        try {
            boolean success = machineService.addMachine(machineDTO);
            if (success) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            log.error("添加机器失败：{}", e.getMessage(), e);
            return Result.error("添加失败：" + e.getMessage());
        }
    }

    @Operation(summary = "更新机器", description = "更新机器信息")
    @PutMapping
    public Result<String> updateMachine(@Validated @RequestBody MachineDTO machineDTO) {
        try {
            boolean success = machineService.updateMachine(machineDTO);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新机器失败：{}", e.getMessage(), e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    @Operation(summary = "删除机器", description = "根据ID删除机器")
    @DeleteMapping("/{machineId}")
    public Result<String> deleteMachine(
            @Parameter(description = "机器ID", required = true) @PathVariable String machineId) {
        try {
            boolean success = machineService.deleteMachine(machineId);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除机器失败：{}", e.getMessage(), e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    @Operation(summary = "批量删除机器", description = "根据ID列表批量删除机器")
    @DeleteMapping("/batch")
    public Result<String> deleteMachines(@RequestBody List<String> machineIds) {
        try {
            boolean success = machineService.deleteMachines(machineIds);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除机器失败：{}", e.getMessage(), e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }

    @Operation(summary = "根据机器类型ID获取机器列表", description = "获取指定机器类型下的所有机器")
    @GetMapping("/type/{machineTypeId}")
    public Result<List<Machine>> getMachinesByTypeId(
            @Parameter(description = "机器类型ID", required = true) @PathVariable String machineTypeId) {
        try {
            List<Machine> machines = machineService.getMachinesByTypeId(machineTypeId);
            return Result.success(machines);
        } catch (Exception e) {
            log.error("根据机器类型获取机器列表失败：{}", e.getMessage(), e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    @Operation(summary = "获取所有空闲机器列表", description = "获取状态为空闲的机器列表")
    @GetMapping("/idle")
    public Result<List<Machine>> getIdleMachines() {
        try {
            List<Machine> machines = machineService.getIdleMachines();
            return Result.success(machines);
        } catch (Exception e) {
            log.error("获取空闲机器列表失败：{}", e.getMessage(), e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    @Operation(summary = "检查机器名称是否存在", description = "检查机器名称是否已被使用")
    @GetMapping("/check-name")
    public Result<Boolean> checkMachineNameExists(
            @Parameter(description = "机器名称", required = true) @RequestParam String machineName,
            @Parameter(description = "排除的机器ID（更新时使用）") @RequestParam(required = false) String excludeId) {
        try {
            boolean exists = machineService.checkMachineNameExists(machineName, excludeId);
            return Result.success(exists);
        } catch (Exception e) {
            log.error("检查机器名称失败：{}", e.getMessage(), e);
            return Result.error("检查失败：" + e.getMessage());
        }
    }

    @Operation(summary = "更新机器状态", description = "更新指定机器的运行状态")
    @PutMapping("/{machineId}/status")
    public Result<String> updateMachineStatus(
            @Parameter(description = "机器ID", required = true) @PathVariable String machineId,
            @Parameter(description = "新状态", required = true) @RequestParam String status) {
        try {
            boolean success = machineService.updateMachineStatus(machineId, status);
            if (success) {
                return Result.success("状态更新成功");
            } else {
                return Result.error("状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新机器状态失败：{}", e.getMessage(), e);
            return Result.error("状态更新失败：" + e.getMessage());
        }
    }
} 